/*
 * @Author: mark
 * @Date: 2023-04-09 10:56:16
 * @LastEditors: mark
 * @LastEditTime: 2023-12-11 21:20:52
 * @FilePath: /pdd/ruoyi-egg/app/service/exportExcel.js
 * @Description: 公共导出模块
 */

// 引入相关模块
const Excel = require("exceljs");
const path = require("path");
const fs = require("fs");
const Service = require("egg").Service;
class ExportExcelService extends Service {
  constructor(ctx) {
    super(ctx);
    this.session = ctx.session;
    this.ResponseCode = ctx.response.ResponseCode;
    this.ServerResponse = ctx.response.ServerResponse;
    this.objUnderlineToHump = ctx.objUnderlineToHump;
    this.objHumpToUnderline = ctx.objHumpToUnderline;
    this.toInt = ctx.toInt;
  }

  /**
   * 通用普通表格的导出
   * @param {*} columns  { header: '列1', key: 'col1', width: 10 },
   * @param {*} data
   */
  async publicDownLoad(columns, data) {
    // 创建excel文件
    const workbook = new Excel.Workbook();
    const worksheet = workbook.addWorksheet("Sheet1");
    worksheet.columns = columns;
    data.forEach((item, index) => {
      let addObj = {};
      columns.forEach((col) => {
        addObj[col.key] = item[col.key];
      });
      worksheet.addRow(addObj);
      // 设置颜色
      // if (item.automap && item.automap === "否") {
      //   worksheet.getCell(`D${index + 2}`).fill = {
      //     type: "pattern",
      //     pattern: "solid",
      //     fgColor: { argb: "FFFF00000" },
      //   };
      // }
    });

    // 生成excel文件流
    const buffer = await workbook.xlsx.writeBuffer();

    // 设置响应头
    this.ctx.set(
      "Content-Type",
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    );
    this.ctx.set("Content-Disposition", "attachment; filename=table.xlsx");

    // 返回excel文件流
    this.ctx.body = buffer;
  }

  /**
   * 下载模块
   * @param {*} moduleName 模块名称
   * @returns
   */
  downLoadExcel(moduleName) {
    let eName = moduleName;
    const filePath = path.join(
      __dirname,
      "..",
      "public",
      "xlsx",
      `${eName}.xlsx`
    );

    if (!fs.existsSync(filePath)) {
      this.ctx.status = 404;
      this.ctx.body = `找不到 ${moduleName}.xlsx 文件！${filePath}`;
      return;
    }
    const stats = fs.statSync(filePath);
    const fileSize = stats.size;
    const range = this.ctx.headers.range;
    if (range) {
      // 处理 Range 请求
      const parts = range.replace(/bytes=/, "").split("-");
      const start = parseInt(parts[0], 10);
      const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
      const chunkSize = end - start + 1;

      const file = fs.createReadStream(filePath, { start, end });
      const headers = {
        "Content-Range": `bytes ${start}-${end}/${fileSize}`,
        "Accept-Ranges": "bytes",
        "Content-Length": chunkSize,
      };

      this.ctx.status = 206;
      this.ctx.set(headers);
      this.ctx.body = file;
    } else {
      // 处理完整请求
      const headers = {
        "Content-Length": fileSize,
        "Content-Disposition": `attachment; filename=${encodeURIComponent(
          moduleName
        )}.xlsx`,
      };

      this.ctx.set(headers);
      this.ctx.body = fs.createReadStream(filePath);
    }
  }
}

module.exports = ExportExcelService;
